package com.example.androidautoproject.service

import android.app.Activity
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.PixelFormat
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.media.Image
import android.media.ImageReader
import android.media.MediaScannerConnection
import android.media.projection.MediaProjection
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Environment
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.provider.MediaStore
import android.util.DisplayMetrics
import android.util.Log
import android.view.WindowManager
import android.widget.Toast
import com.example.androidautoproject.MainActivity
import com.example.androidautoproject.R
import com.example.androidautoproject.utils.AdParam
import com.example.androidautoproject.utils.ScreenshotUtil
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

class ScreenCaptureForegroundService: Service() {
    private lateinit var mediaProjectionManager: MediaProjectionManager
    private var mediaProjection: MediaProjection? = null
    private var imageReader: ImageReader? = null
    override fun onCreate() {
        super.onCreate()
        mediaProjectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        when (intent?.action) {
            "ACTION_START_CAPTURE" -> {
                val resultCode = intent.getIntExtra("EXTRA_RESULT_CODE", -1)
                val data: Intent? = intent.getParcelableExtra("EXTRA_RESULT_DATA")

                if (resultCode != Activity.RESULT_OK || data == null) {
                    stopSelf()
                    return START_NOT_STICKY
                }

                // 1. 首先创建并显示通知，将服务设置为前台服务
                val notification = createNotification()
                startForeground(NOTIFICATION_ID, notification)

                // 2. 然后在显示通知后，再初始化 MediaProjection
                try {
                    mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data)
                    Log.e(TAG, "mediaProjection ${mediaProjection}")
                    // 初始化成功，现在可以开始屏幕捕获了 (例如创建 VirtualDisplay)
                    // 启动目标应用并延迟截图
                    val launchIntent = packageManager.getLaunchIntentForPackage(AdParam.screenPackageName)
                    launchIntent?.let {
                        startActivity(it)
                        Handler(Looper.getMainLooper()).postDelayed({
                            startScreenCapture() // 您的自定义方法
                        }, 5000)
                    }
                } catch (e: SecurityException) {
                    Log.e(TAG, "Error getting media projection!", e)
                    stopSelf()
                }
            }
            else -> {
                stopSelf()
            }
        }
        return START_STICKY
    }

    private fun createNotification(): Notification {
        // 创建一个通知渠道 (针对 Android O 及以上版本)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "Screen Capture",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "Screen is being captured"
            }
            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }

        // 构建通知
        val builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Notification.Builder(this, CHANNEL_ID)
        } else {
            Notification.Builder(this)
        }

        return builder
            .setContentTitle("Screen Capture")
            .setContentText("Capturing screen content...")
            .setSmallIcon(R.drawable.ic_launcher_foreground) // 请使用您自己的图标
            .setOngoing(true)
            .build()
    }

    private fun startScreenCapture() {
        // 在这里使用 mediaProjection 创建 VirtualDisplay 并进行屏幕捕获
        // 例如：val virtualDisplay = mediaProjection?.createVirtualDisplay(...)
        Log.d(TAG, "Screen capture started successfully.")
        val metrics = DisplayMetrics()
        val windowManager = getSystemService(WindowManager::class.java)
        windowManager.defaultDisplay.getRealMetrics(metrics)
        val width = metrics.widthPixels
        val height = metrics.heightPixels
        val density = metrics.densityDpi

        imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2)
        try {
            val virtualDisplay = mediaProjection?.createVirtualDisplay(
                "ScreenCapture",
                width, height, density,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                imageReader?.surface, null, null
            )

            Log.e(TAG, "VirtualDisplay created: $virtualDisplay")

            Handler(Looper.getMainLooper()).postDelayed({
                val image = imageReader?.acquireLatestImage()
                if (image != null) {
                    // 处理图像...
                    val planes = image.planes
                    val buffer = planes[0].buffer
                    val pixelStride = planes[0].pixelStride
                    val rowStride = planes[0].rowStride
                    val rowPadding = rowStride - pixelStride * width

                    val bitmap = Bitmap.createBitmap(
                        width + rowPadding / pixelStride,
                        height,
                        Bitmap.Config.ARGB_8888
                    )
                    bitmap.copyPixelsFromBuffer(buffer)
                    var bs64 = ScreenshotUtil.bitmapToBase64(bitmap)
                    ScreenshotUtil.base64 = bs64
                    // 保存截图
                    saveScreenshot(bitmap)

                    image.close()
                }

                virtualDisplay?.release()
                mediaProjection?.stop()
            }, 1000)
        } catch (e: SecurityException) {
            Log.e(TAG, "SecurityException: ${e.message}")
            Toast.makeText(this, "Permission error: ${e.message}", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Log.e(TAG, "Error creating media projection: ${e.message}")
        }
    }

    private fun saveScreenshot(bitmap: Bitmap) {
        // 保存截图的逻辑
        // 注意：在 Android 10 (API 29) 及以上版本，推荐使用 MediaStore
        try {
            val filename = "screenshot_${System.currentTimeMillis()}.png"
            val contentValues = ContentValues().apply {
                put(MediaStore.Images.Media.DISPLAY_NAME, filename)
                put(MediaStore.Images.Media.MIME_TYPE, "image/png")
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + "/androidAutoProject/")
                }
            }

            val resolver = contentResolver
            val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
            uri?.let {
                resolver.openOutputStream(it)?.use { outputStream ->
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
                }
            }
        } catch (e: Exception) {
            Log.e("Screenshot", "Save screenshot failed", e)
        }
    }

    private fun saveBitmapToFile(bitmap: Bitmap) {
        // 示例：将 bitmap 保存到外部存储的 Pictures 目录
        try {
            val filename = "screenshot_${System.currentTimeMillis()}.png"
            val imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            if (!imagesDir.exists()) {
                imagesDir.mkdirs()
            }
            val imageFile = File(imagesDir, filename)
            FileOutputStream(imageFile).use { out ->
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
            }
            // 通知图库更新
            MediaScannerConnection.scanFile(
                this,
                arrayOf(imageFile.absolutePath),
                arrayOf("image/png"),
                null
            )
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onDestroy() {
        super.onDestroy()
        // 释放资源
        releaseScreenCapture()
    }
    private fun releaseScreenCapture() {
        // virtualDisplay?.release()
        // virtualDisplay = null
        imageReader?.close()
        imageReader = null
        mediaProjection?.stop()
        mediaProjection = null
    }
    companion object {
        private const val TAG = "CaptureService"
        private const val CHANNEL_ID = "screen_capture_channel"
        private const val NOTIFICATION_ID = 12345 // 唯一通知ID
    }


}